package models

import (
	"gitchina/smartguard-api/data"
	"gitchina/smartguard-api/errors"
	"gitchina/smartguard-api/util"
	"time"
)

var ConnectedSchool *util.SafeMap

const (
	FUNC_SCHOOL_CHANGED = "school.addOrUpdate"
)

type School struct {
	ID              string    `json:"id"`
	Name            string    `json:"name"`
	Remark          string    `json:"remark"`
	Data            string    `json:"data"`
	LocalIP         string    `json:"local_ip"`
	LastConnectTime time.Time `json:"-"`
}

func init() {
	ConnectedSchool = util.NewSafeMap()
	go killZombie()
}

func ListSchool() (list []School, err error) {
	return nil, nil
}

func (s *School) Load() error {
	return nil
}

func (s School) AddOrUpdate() bool {
	ok := true
	if err := data.AddOrUpdateSchool(data.School{
		Name:       s.Name,
		Data:       s.Data,
		Remark:     s.Remark,
		CreateTime: "nil",
		UpdateTime: "nil",
	}); err != nil {
		ok = false
		util.WriteLog(errors.New(FUNC_SCHOOL_CHANGED, err.Error()))
	}
	return ok
}

func (s School) Connect() {
	s.LastConnectTime = time.Now()
	ConnectedSchool.Set(s.ID, s)
}

func GetConnectedSchool(id string) (school *School) {
	if val, ok := ConnectedSchool.Get(id); ok {
		temp := val.(School)
		school = &temp
	}
	return
}

func GetAllConnectedSchools() []interface{} {
	return ConnectedSchool.IterAllValues()
}

func killZombie() {
	t1 := time.NewTimer(time.Minute)
	for {
		select {
		case <-t1.C:
			for _, v := range GetAllConnectedSchools() {
				school := v.(School)
				if time.Since(school.LastConnectTime) > 3*time.Minute {
					ConnectedSchool.Remove(school.ID)
				}
			}
			t1.Reset(time.Minute)
		}
	}
}
